import json
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from booktest.models import BookInfo, HeroInfo

from rest_framework import serializers
from .serializers import HeroSerializer, HeroModelSerializer
from .serializers import BookSerializer, BookModelSerializer


class BooksView(View):
    def get(self, request):
        """查询所有"""
        # 处理
        book_list = BookInfo.objects.all()

        serializer = BookSerializer(book_list, many=True)
        book_dict_list = serializer.data
        # 将对象转字典
        # book_dict_list = []
        # for book in book_list:
        #     book_dict_list.append({
        #         'id': book.id,
        #         'btitle': book.btitle,
        #         'bpub_date': book.bpub_date
        #     })

        return JsonResponse(book_dict_list, safe=False)

    def post(self, request):
        """增加"""
        param_dict = json.loads(request.body.decode())

        # serializer = BookSerializer(data=param_dict)
        serializer = BookModelSerializer(data=param_dict)
        if serializer.is_valid():
            book = serializer.save()
            # serializer = BookSerializer(book)
            serializer = BookModelSerializer(book)
            book_dict = serializer.data
            return JsonResponse(book_dict, status=201)
        else:
            return JsonResponse(serializer.errors)

        # btitle = param_dict.get('btitle')
        # bpub_date = param_dict.get('bpub_date')

        # # 验证
        # if not all([btitle, bpub_date]):
        #     return JsonResponse({'error': '缺少必传参数'})
        #
        # # 处理
        # book = BookInfo.objects.create(btitle=btitle, bpub_date=bpub_date)
        #
        # # 将对象转字典
        # book_dict = {
        #     'id': book.id,
        #     'btitle': book.btitle,
        #     'bpub_date': book.bpub_date
        # }

        # return JsonResponse(book_dict, status=201)


class BookView(View):
    def get(self, request, pk):
        # 根据主键查询对象
        book = BookInfo.objects.get(pk=pk)

        # serializer = BookSerializer(book)
        serializer = BookModelSerializer(book)
        book_dict = serializer.data

        # try:
        #     book = BookInfo.objects.get(pk=pk)
        # except:
        #     return JsonResponse({'error': '图书编号无效'})

        # book_dict = {
        #     'id': book.id,
        #     'btitle': book.btitle,
        #     'bpub_date': book.bpub_date
        # }

        return JsonResponse(book_dict)

    def put(self, request, pk):
        # 根据主键修改对象
        # 接收
        param_dict = json.loads(request.body.decode())

        book = BookInfo.objects.get(pk=pk)
        serializer = BookSerializer(book, data=param_dict, )

        if serializer.is_valid():
            book = serializer.save()
            serializer = BookSerializer(book)
            book_dict = serializer.data

            return JsonResponse(book_dict, status=201)
        else:
            return JsonResponse(serializer.errors)

        # btitle = param_dict.get('btitle')
        # bpub_date = param_dict.get('bpub_date')

        # 处理
        # try:
        #     book = BookInfo.objects.get(pk=pk)
        # except:
        #     return JsonResponse({'error': '图书编号无效'})

        # book.btitle = btitle
        # book.bpub_date = bpub_date
        # book.save()

        # # 将对象转字典
        # book_dict = {
        #     'id': book.id,
        #     'btitle': book.btitle,
        #     'bpub_date': book.bpub_date
        # }

        # return JsonResponse(book_dict, status=201)

    def delete(self, request, pk):
        # 根据主键删除对象
        try:
            book = BookInfo.objects.get(pk=pk)
        except:
            return JsonResponse('error', '图书编号无效')
        book.delete()

        return JsonResponse({}, status=204)

        # book = BookInfo.objects.get(pk=pk)
        # serializer = BookSerializer(book)
        # if serializer.is_valid():
        #     book = serializer.save()
        #     book.delete()
        #     return JsonResponse({}, status=204)
        # else:
        #     return JsonResponse(serializer.errors)


# from rest_framework.viewsets import ModelViewSet
# from .serializers import BookModelSerializer


# class BookModelViewSet(ModelViewSet):
#     queryset = BookInfo.objects.all()
#     serializer_class = BookModelSerializer


class HerosView(View):
    def get(self, request):
        hero_list = HeroInfo.objects.all()
        # hero_list = HeroInfo.objects.filter(id__lt=5)
        serializer = HeroSerializer(hero_list, many=True)
        # serializer = HeroModelSerializer(hero_list, many=True)

        hero_dict_list = serializer.data
        return JsonResponse(hero_dict_list, safe=False)

    def post(self, request):
        param_dict = json.loads(request.body.decode())
        # serializer = HeroSerializer(data=param_dict)
        serializer = HeroModelSerializer(data=param_dict)
        if serializer.is_valid():
            hero = serializer.save()
            # serializer = HeroSerializer(hero)
            serializer = HeroModelSerializer(hero)
            hero_dict = serializer.data

            return JsonResponse(hero_dict, status=201)
        else:
            return JsonResponse(serializer.errors)


class HeroView(View):
    def get(self, request, pk):
        hero_dict = HeroInfo.objects.get(pk=pk)

        serializer = HeroModelSerializer(hero_dict)
        hero_list = serializer.data
        return JsonResponse(hero_list, safe=False)

    def put(self, request, pk):
        param_dict = json.loads(request.body.decode())

        hero = HeroInfo.objects.get(pk=pk)
        serializer = HeroSerializer(hero, data=param_dict)

        if serializer.is_valid():
            hero = serializer.save()
            serializer = HeroSerializer(hero)
            hero_dict = serializer.data
            return JsonResponse(hero_dict, status=201)
        else:
            return JsonResponse(serializer.errors)

    def delete(self, request, pk):
        try:
            hero = HeroInfo.objects.get(pk=pk)
        except:
            return JsonResponse('error', '英雄编号无效')
        hero.delete()
        return JsonResponse({}, status=204)